package fm.dongman.modellib.source;

import android.support.annotation.NonNull;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import fm.dongman.animefm.contractlib.BaseDataSource;
import fm.dongman.animefm.contractlib.IModel;
import fm.dongman.animefm.contractlib.contract.UserInfoContract;
import fm.dongman.modellib.RemoteHelper;
import fm.dongman.modellib.StaticArea.StaticUrl;
import fm.dongman.modellib.remote.RemoteOperationHelper;

/**
 * 用户详情
 * Created by KUIGE on 2017/10/29.
 */

public class UserInfoRepository implements UserInfoContract.IUserInfoDataSource {
    private static UserInfoRepository SINGLETON;
    private RemoteOperationHelper mRemote;
    private String mId;

    private UserInfoRepository() {
        mRemote = RemoteOperationHelper.getOperationHelper();
    }

    public static UserInfoRepository getInstance() {
        if (SINGLETON == null) {
            SINGLETON = new UserInfoRepository();
        }
        return SINGLETON;
    }

    @Override
    public void setUserId(@NonNull String id) {
        mId = id;
    }

    @Override
    public void followUser(int follow, @NotNull String followedId, LoadSourceCallback<? super String> callback) {
        HashMap<String, String> mapHan = new HashMap<>();
        mapHan.put("x-token", StaticUrl.TOKEN_KEY);
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("follow_user_id", followedId);
        String type = "follow";
        if (follow == 0) {
            type = "unfollow";
        }
        hashMap.put("type", type);
        JSONObject jsonObject = RemoteHelper.Companion.getInstance().parsePostUrl("http://api.dongman.fm/account/followUser", mapHan, hashMap);
        if (jsonObject == null) {
            callback.onDataLoadFiled();
            return;
        }
        callback.onDataLoaded(null);
    }

    @Override
    public void getData(@NonNull BaseDataSource.LoadSourceCallback<? super IModel.IUserModel> callback) {
        HashMap<String, String> mapHan = new HashMap<>();
        mapHan.put("x-token", StaticUrl.TOKEN_KEY);
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("id", mId);
        JSONObject object = RemoteHelper.Companion.getInstance().parsePostUrl(StaticUrl.USER_PAGE, mapHan, hashMap);
        if (object == null) {
            callback.onDataLoadFiled();
            return;
        }
        callback.onDataLoaded(mRemote.downUserInfo(object));
    }

    @Override
    public void saveData(IModel.IUserModel dataModel) {
    }

    @Override
    public void refreshData() {
    }

    @Override
    public void offLine() {
    }
}
